package org.an.proj.contacts.net.service.retrofit.util;

import com.google.gson.Gson;
import java.util.concurrent.TimeUnit;
import link.config.StoreConfig;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.config.Config;
import org.an.proj.contacts.config.UriConfig;
import org.an.proj.contacts.net.service.retrofit.coverter.GsonConverterFactory;
import org.an.proj.contacts.net.service.retrofit.interceptor.HeaderInterceptor;
import org.an.proj.contacts.net.service.retrofit.interceptor.HttpLoggingInterceptor;
import org.an.proj.contacts.net.service.retrofit.upload.DownloadInterceptor;
import org.an.proj.contacts.net.service.retrofit.upload.ProgressListener;
import org.an.proj.contacts.net.service.retrofit.upload.UIProgressListener;
import org.an.proj.contacts.net.service.retrofit.upload.UploadProgressInterceptor;
import org.an.proj.contacts.util.AppUtil;
import org.an.proj.contacts.util.DataParseUtil;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * 创建时间：2016年10月10日11:10 <br>
 * 作者：fuchaoyang <br>
 * 描述：这里为了少创建，不采用url不同 Builder.baseUrl("").builder()的方式每次创建
 * （如果baseUrl过多可使用上述方式避免使用过多静态数据）
 */
public class ServiceGenerator {
  private static Retrofit sGithubRetrofit;
  private static Retrofit sAPIRetrofit;
  private static Retrofit sMobileRetrofit;
  // 登录相关
  private static Retrofit.Builder sMobileRetrofitBuilder;
  // 其他api相关
  private static Retrofit.Builder sApiRetrofitBuilder;
  private static Retrofit.Builder sGithubRetrofitBuilder;
  private static OkHttpClient.Builder sHttpClientBuilder = new OkHttpClient.Builder();

  static {
    // 配置超时
    sHttpClientBuilder.connectTimeout(1, TimeUnit.MINUTES)
        .readTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(1, TimeUnit.MINUTES);
    // 设置超时时间 具体时长待定
    //.addNetworkInterceptor(new UploadProgressInterceptor(progressListener))
    //.addInterceptor()

    // 请求头
    HeaderInterceptor headerInterceptor = new HeaderInterceptor() {
      @Override public void initHeaders() {
        // 内部已经对null做了处理，如果为null不会添加
        addHead("Lianjia-access-token", StoreConfig.getInstance().getToken()).addHead(
            "Lianjia-App-Id", "lianjia-im").addHead("im-version", "1")//im版本, 0表示leancloud, 1表示链家im;
            .addHead("User-Agent", AppUtil.getUserAgent(MyApplication.getInstance(), "LINKNH/"));
        //.addHead("versionName",Config.VERSION_NAME)
        //.addHead("versionCode",String.valueOf(Config.VERSION_CODE))
      }
    };

    sHttpClientBuilder.addInterceptor(headerInterceptor);

    // debug模式下打log
    if (Config.IS_LOG_ENABLE) {
      HttpLoggingInterceptor loggingInterceptor = HttpLoggingInterceptor.createLoggingInterceptor()
          .setLevel(HttpLoggingInterceptor.Level.BODY);
      sHttpClientBuilder.addInterceptor(loggingInterceptor);
    }

    //  初始化retrofitBuilder
    sMobileRetrofitBuilder = generateRetrofitBuilder(DataParseUtil.mGson);
    sApiRetrofitBuilder = generateRetrofitBuilder(DataParseUtil.mGson);
    sGithubRetrofitBuilder = generateRetrofitBuilder(DataParseUtil.mGithubGson);
  }

  private static Retrofit.Builder generateRetrofitBuilder(Gson gson) {
    return new Retrofit.Builder()
        //.addCallAdapterFactory(LinkCallAdapterFactory.created())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        //.addConverterFactory(GsonConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson)).client(sHttpClientBuilder.build());
  }

  /**
   * 创建api Service
   */
  public static <S> S createService(Class<S> serviceClass) {
    if (sAPIRetrofit == null || !sAPIRetrofit.baseUrl()
        .equals(HttpUrl.parse(UriConfig.getLinkUriBase()))) {
      sAPIRetrofit = sApiRetrofitBuilder.baseUrl(UriConfig.getLinkUriBase()).build();
    }

    return sAPIRetrofit.create(serviceClass);
  }

  /**
   * 创建登录相关 Service
   */
  public static <S> S createMobileService(Class<S> serviceClass) {
    if (sMobileRetrofit == null || !sMobileRetrofit.baseUrl()
        .equals(HttpUrl.parse(UriConfig.getMobileUriBase()))) {
      sMobileRetrofit = sMobileRetrofitBuilder.baseUrl(UriConfig.getMobileUriBase()).build();
    }

    return sMobileRetrofit.create(serviceClass);
  }

  /**
   * 创建github Service
   */
  public static <S> S createGithubService(Class<S> serviceClass) {
    if (sGithubRetrofit == null || !sGithubRetrofit.baseUrl()
        .equals(HttpUrl.parse(UriConfig.getGithubUriBase()))) {
      sGithubRetrofit = sGithubRetrofitBuilder.baseUrl(UriConfig.getGithubUriBase()).build();
    }

    return sGithubRetrofit.create(serviceClass);
  }

  /**
   * 创建 上传 Service
   * 每次都会重新创建 okhttp 和 retrofit,所以不会影响其他请求
   *
   * @param listener 上传进度回调 在线程中{@link UIProgressListener}
   */
  public static <S> S createService(Class<S> serviceClass, ProgressListener listener) {
    UploadProgressInterceptor progressInterceptor = new UploadProgressInterceptor(listener);
    Retrofit linkRetrofit = sApiRetrofitBuilder.client(
        sHttpClientBuilder.addNetworkInterceptor(progressInterceptor).build())
        .baseUrl(UriConfig.getLinkUriBase())
        .build();
    // 构造Retrofit之后就移除
    sHttpClientBuilder.networkInterceptors().remove(progressInterceptor);

    return linkRetrofit.create(serviceClass);
  }

  /**
   * 创建 上传 Service
   * 每次都会重新创建 okhttp 和 retrofit,所以不会影响其他请求
   *
   * @param listener 上传进度回调 在线程中{@link UIProgressListener}
   */
  public static <S> S createDownloadService(Class<S> serviceClass, ProgressListener listener) {
    DownloadInterceptor progressInterceptor = new DownloadInterceptor(listener);
    Retrofit linkRetrofit = sApiRetrofitBuilder.client(
        sHttpClientBuilder.addNetworkInterceptor(progressInterceptor).build())
        .baseUrl(UriConfig.getLinkUriBase())
        .build();
    // 构造Retrofit之后就移除
    sHttpClientBuilder.networkInterceptors().remove(progressInterceptor);

    return linkRetrofit.create(serviceClass);
  }
}
